<template>
  <div class="chat-msg-item">
    <div class="chat-msg-tip"
         v-if="msgInfo.type == $enums.MESSAGE_TYPE.RECALL || msgInfo.type == $enums.MESSAGE_TYPE.TIP_TEXT">
      {{ msgInfo.content }}
    </div>
    <div class="chat-msg-tip" v-if="msgInfo.type == $enums.MESSAGE_TYPE.TIP_TIME">
      {{ $date.toTimeText(msgInfo.sendTime) }}
    </div>
    <div class="chat-msg-normal" v-if="isNormal" :class="{ 'chat-msg-mine': mine }">
      <!-- Add check box -->
      <div class="msg-checkbox" v-show="showCheckbox">
        <el-checkbox
            :value="checked"
            @change="$emit('check-change', $event)"
        ></el-checkbox>
      </div>
      <!--			<div class="head-image">-->
      <!--				<head-image :name="showName" :size="38" :url="headImage" :id="msgInfo.sendId"></head-image>-->
      <!--			</div>-->
      <div class="chat-msg-content">
        <div v-show="mode == 1 && msgInfo.groupId && !msgInfo.selfSend" class="chat-msg-top">
          <span>{{ showName }}</span>
        </div>
        <div v-show="mode == 2" class="chat-msg-top">
          <span>{{ showName }}</span>
          <span>{{ $date.toTimeText(msgInfo.sendTime) }}</span>
        </div>
        <div class="chat-msg-bottom" @contextmenu.prevent="showRightMenu($event)">
          <div ref="chatMsgBox">
						<span class="chat-msg-text" v-if="msgInfo.type == $enums.MESSAGE_TYPE.TEXT"
                  v-html="$emo.transform(parseContent(msgInfo))"></span>
            <div class="chat-msg-image" v-if="msgInfo.type == $enums.MESSAGE_TYPE.IMAGE">
              <div class="img-load-box" v-loading="loading" element-loading-text="Uploading.."
                   element-loading-background="rgba(0, 0, 0, 0.4)">
                <img class="send-image" :src1="JSON.parse(msgInfo.content).thumbUrl+'.jpg'" :src="base64Data"
                     @click="showFullImageBox()" loading="lazy" />
              </div>
              <span title="Send failed" v-show="loadFail" @click="onSendFail"
                    class="send-fail el-icon-warning"></span>
            </div>
            <div class="chat-msg-file" v-if="msgInfo.type == $enums.MESSAGE_TYPE.FILE">
              <div class="chat-file-box" v-loading="loading">
                <div class="chat-file-info">
                  <!--									<el-link class="chat-file-name" :underline="true" target="_blank" type="primary"-->
                  <!--										:href1="data.url.originUrl" :download="data.name">{{ data.name }}</el-link>-->
                  <el-button  type="text" class="chat-file-name"
                              @click1="down(msgInfo)">{{ data.name }}</el-button>
                  <div class="chat-file-size">{{ fileSize }}</div>
                </div>
                <div class="chat-file-icon">
                  <span type="primary" class="el-icon-document"></span>
                </div>
              </div>
              <span title="Send failed" v-show="loadFail" @click="onSendFail"
                    class="send-fail el-icon-warning"></span>
            </div>
          </div>
          <div class="chat-msg-voice" v-if="msgInfo.type == $enums.MESSAGE_TYPE.AUDIO" @click="onPlayVoice()">
            <audio controls :src1="JSON.parse(msgInfo.content).url" :src="base64Data"></audio>
          </div>
          <div class="chat-action chat-msg-text" v-if="isAction">
						<span v-if="msgInfo.type == $enums.MESSAGE_TYPE.ACT_RT_VOICE" title="Recall" @click="$emit('call')"
                  class="iconfont icon-chat-voice"></span>
            <span v-if="msgInfo.type == $enums.MESSAGE_TYPE.ACT_RT_VIDEO" title="Recall" @click="$emit('call')"
                  class="iconfont icon-chat-video"></span>
            <span>{{ msgInfo.content }}</span>
          </div>
          <div class="chat-msg-status" v-if="!isAction">
						<span class="chat-readed" v-show="msgInfo.selfSend && !msgInfo.groupId
							&& msgInfo.status == $enums.MESSAGE_STATUS.READED">Read</span>
            <span class="chat-unread" v-show="msgInfo.selfSend && !msgInfo.groupId
							&& msgInfo.status != $enums.MESSAGE_STATUS.READED">Unread</span>
          </div>
          <div class="chat-receipt" v-show="false && msgInfo.receipt" @click="onShowReadedBox">
            <span v-if="msgInfo.receiptOk" class="icon iconfont icon-ok" title="All read"></span>
            <span v-else>{{ msgInfo.readedCount }} people have read</span>
          </div>
        </div>
      </div>
    </div>
    <right-menu v-if="menu && rightMenu.show" :pos="rightMenu.pos" :items="menuItems"
                @close="rightMenu.show = false" @select="onSelectMenu"></right-menu>
    <chat-group-readed ref="chatGroupReadedBox" :msgInfo="msgInfo" :groupMembers="groupMembers"></chat-group-readed>
  </div>
</template>

<script>
import HeadImage from "../common/HeadImage.vue";
import RightMenu from '../common/RightMenu.vue';
import ChatGroupReaded from './ChatGroupReaded.vue';
import {CryptoUtil} from "@/api/cryptoUtil";
import {MESSAGE_TYPE} from "@/api/enums";

export default {
  name: "messageItem",
  components: {
    HeadImage,
    RightMenu,
    ChatGroupReaded
  },
  props: {
    showCheckbox: Boolean,
    checked: Boolean,
    mode: {
      type: Number,
      default: 1
    },
    mine: {
      type: Boolean,
      required: true
    },
    headImage: {
      type: String,
      required: true
    },
    showName: {
      type: String,
      required: true
    },
    msgInfo: {
      type: Object,
      required: true
    },
    groupMembers: {
      type: Array
    },
    menu: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      audioPlayState: 'STOP',
      rightMenu: {
        show: false,
        pos: {
          x: 0,
          y: 0
        }
      },
      base64Data: undefined,
    }
  },
  mounted: function () {
    console.log('mounted', this.msgInfo, this.msgInfo.content)

    switch (this.msgInfo.type) {
      case MESSAGE_TYPE.TEXT:
        return;
      case MESSAGE_TYPE.IMAGE:
      case MESSAGE_TYPE.AUDIO:
        console.log('load img', this.msgInfo)
        if (this.msgInfo.sendCke) {
          var cryptoInstance = this.$store.getters.cryptoInstance();
          cryptoInstance.cryptoUtil.decryptFileReal(cryptoInstance, JSON.parse(this.msgInfo.content).originUrl)
              .then(decryptedFile => {
                var reader = new FileReader();
                reader = new FileReader();
                reader.readAsDataURL(decryptedFile);
                reader.onload = () => { this.base64Data = reader.result };
              });

        } else {
          this.base64Data = JSON.parse(this.msgInfo.content).originUrl
        }

        return;
      case MESSAGE_TYPE.FILE:
        return;
    }

  },
  methods: {
    onSendFail() {
      this.$message.error("The file has failed to be sent. Automatic resending is not currently supported. Manual resending is recommended.")
    },
    showFullImageBox() {
      let imageUrl = JSON.parse(this.msgInfo.content).originUrl;
      if (imageUrl) {
        this.$store.commit('showFullImageBox', imageUrl);
      }
    },
    onPlayVoice() {
      if (!this.audio) {
        this.audio = new Audio();
      }
      this.audio.src = JSON.parse(this.msgInfo.content).url;
      this.audio.play();
      this.onPlayVoice = 'RUNNING';
    },
    showRightMenu(e) {
      // default menu width
      const menuWidth = 150
      const menuHeight = 150;
      let x = e.x
      let y = e.y
      // right is bounding?
      if (x + menuWidth > window.innerWidth) {
        x = window.innerWidth - menuWidth;
      }
      // bottom is bounding?
      if (y + menuHeight > window.innerHeight) {
        y = window.innerHeight - menuHeight;
      }

      this.rightMenu.pos = {x, y};
      this.rightMenu.show = true;
    },
    onSelectMenu(item) {
      if (item.key === 'BATCH_DELETE') {
        this.$emit('batch-delete');
      } else {
        this.$emit(item.key.toLowerCase(), this.msgInfo); //delete recall
      }
    },
    onShowReadedBox() {
      let rect = this.$refs.chatMsgBox.getBoundingClientRect();
      this.$refs.chatGroupReadedBox.open(rect);
    },
    down(msgInfo) {
      console.log(msgInfo)

    },
    parseContent(msgInfo) {
      return msgInfo.content
      // var a = true
      // if (a) {
      //   if (msgInfo.encry) {
      //     var cke = msgInfo.sendCke
      //     if (!this.mine) {
      //       cke = msgInfo.recvCke
      //     }
      //     return JSON.stringify({
      //       code: msgInfo.encry,
      //       psha256: sessionStorage.getItem("psha256"),
      //       cke,
      //       encry: msgInfo.encry,
      //       content: msgInfo.content
      //     })
      //   }
      //   return msgInfo.content
      //   // return msgInfo.extra
      // }
      // try {
      //   var keyEncry = msgInfo.sendCke
      //   // if (!this.mine) {
      //   //   keyEncry = msgInfo.recvCke
      //   // }
      //   var code = Number(sessionStorage.getItem("code"));
      //   var cryptoUtil = new CryptoUtil(code);
      //   var keyForKeyObj = cryptoUtil.randomKeyObj(sessionStorage.getItem("psha256"))
      //   console.log('keyForKeyObj', keyForKeyObj, keyEncry)
      //   var keyObj = cryptoUtil.decode(keyForKeyObj, keyEncry)
      //   console.log('keyObj', keyObj);
      //   var content = cryptoUtil.decode(JSON.parse(keyObj), msgInfo.content)
      //   // return new CryptoUtil(code).decode(keyObj, t) + '-' + t
      //   return content
      // } catch (e) {
      //   console.log(e)
      //   return msgInfo.content
      // }
    }
  },
  computed: {
    loading() {
      return this.msgInfo.loadStatus && this.msgInfo.loadStatus === "loading";
    },
    loadFail() {
      return this.msgInfo.loadStatus && this.msgInfo.loadStatus === "fail";
    },
    data() {
      return JSON.parse(this.msgInfo.content)
    },
    fileSize() {
      let size = this.data.size;
      if (size > 1024 * 1024) {
        return Math.round(size / 1024 / 1024) + "M";
      }
      if (size > 1024) {
        return Math.round(size / 1024) + "KB";
      }
      return size + "B";
    },
    menuItems() {
      let items = [];
      items.push({
        key: 'DELETE',
        name: 'DELETE',
        icon: 'el-icon-delete'
      }, {
        key: 'BATCH_DELETE',
        name: 'BATCH DELETE',
        icon: 'el-icon-delete'
      });
      if (this.msgInfo.selfSend && this.msgInfo.id > 0) {
        items.push({
          key: 'RECALL',
          name: 'RECALL',
          icon: 'el-icon-refresh-left'
        });
      }
      return items;
    },
    isAction() {
      return this.$msgType.isAction(this.msgInfo.type);
    },
    isNormal() {
      const type = this.msgInfo.type;
      return this.$msgType.isNormal(type) || this.$msgType.isAction(type)
    }
  }
}
</script>

<style lang="scss">
.chat-msg-item {

  .chat-msg-tip {
    text-align: center;
    line-height: 50px;
    font-size: var(--im-font-size-small);
    color: var(--im-text-color-light);
  }

  .chat-msg-normal {
    position: relative;
    font-size: 0;
    //padding-left: 48px;
    min-height: 50px;
    margin-top: 10px;

    .msg-checkbox {
      position: absolute;
      //left: -20px;
      left: -25px;
      top: 20px; /* Half the height of head image at 40px */
      transform: translateY(-50%);
    }

    .head-image {
      position: absolute;
      width: 40px;
      height: 40px;
      top: 0;
      left: 0;
    }

    .chat-msg-content {
      width: 100%;
      text-align: left;

      .send-fail {
        color: #e60c0c;
        font-size: 30px;
        cursor: pointer;
        margin: 0 20px;
      }

      .chat-msg-top {
        display: flex;
        flex-wrap: nowrap;
        color: var(--im-text-color-light);
        font-size: var(--im-font-size);
        line-height: 20px;

        span {
          margin-right: 12px;
        }
      }

      .chat-msg-bottom {
        display: inline-block;
        //padding-right: 300px;
        padding-left: 5px;

        .chat-msg-text {
          display: block;
          position: relative;
          line-height: 26px;
          //margin-top: 3px;
          padding: 6px 10px;
          background-color: var(--im-background);
          border-radius: 10px;
          font-size: var(--im-font-size);
          text-align: left;
          width: 100%;
          min-width: 30px;
          min-height: 35px;
          white-space: pre-wrap;
          word-break: break-all;

          &:after {
            content: "";
            position: absolute;
            left: -10px;
            top: 13px;
            width: 0;
            height: 0;
            border-style: solid dashed dashed;
            border-color: #eee transparent transparent;
            overflow: hidden;
            border-width: 10px;
          }
        }

        .chat-msg-image {
          display: flex;
          flex-wrap: nowrap;
          flex-direction: row;
          align-items: center;

          .send-image {
            min-width: 40px;
            min-height: 30px;
            max-width: 100px;
            max-height: 130px;
            border-radius: 8px;
            cursor: pointer;
          }

        }

        .chat-msg-file {
          display: flex;
          flex-wrap: nowrap;
          flex-direction: row;
          align-items: center;
          cursor: pointer;
          margin-bottom: 2px;

          .chat-file-box {
            display: flex;
            flex-wrap: nowrap;
            align-items: center;
            min-height: 60px;
            box-shadow: var(--im-box-shadow-light);
            border-radius: 4px;
            padding: 10px 15px;

            .chat-file-info {
              flex: 1;
              height: 100%;
              text-align: left;
              font-size: 14px;
              margin-right: 10px;

              .chat-file-name {
                display: inline-block;
                min-width: 130px;
                max-width: 220px;
                font-size: 14px;
                margin-bottom: 4px;
                white-space: pre-wrap;
                word-break: break-all;
                padding: 0 !important;
                text-align: left;
              }

              .chat-file-size {
                font-size: var(--im-font-size-smaller);
                color: var(--im-text-color-light);
              }
            }

            .chat-file-icon {
              font-size: 44px;
              color: #d42e07;
            }
          }

          .send-fail {
            color: #e60c0c;
            font-size: 30px;
            cursor: pointer;
            margin: 0 20px;
          }

        }

        .chat-msg-voice {
          font-size: 14px;
          cursor: pointer;

          audio {
            height: 45px;
            padding: 5px 0;
          }
        }

        .chat-action {
          display: flex;
          align-items: center;

          .iconfont {
            cursor: pointer;
            font-size: 22px;
            padding-right: 8px;
          }
        }

        .chat-msg-status {
          display: block;

          .chat-readed {
            font-size: 12px;
            color: var(--im-text-color-light);
          }

          .chat-unread {
            font-size: var(--im-font-size-smaller);
            color: var(--im-color-danger);
          }
        }

        .chat-receipt {
          font-size: var(--im-font-size-smaller);
          cursor: pointer;
          color: var(--im-text-color-light);

          .icon-ok {
            font-size: 20px;
            color: var(--im-color-sucess);
          }
        }

        .chat-at-user {
          padding: 2px 5px;
          border-radius: 3px;
          cursor: pointer;
        }
      }
    }


    &.chat-msg-mine {
      text-align: right;
      padding-left: 0;
      //padding-right: 48px;

      .head-image {
        left: auto;
        right: 0;
      }

      .chat-msg-content {
        text-align: right;

        .chat-msg-top {
          flex-direction: row-reverse;

          span {
            margin-left: 12px;
            margin-right: 0;
          }
        }

        .chat-msg-bottom {
          //padding-left: 180px;
          padding-right: 5px;

          .chat-msg-text {
            margin-left: 10px;
            background-color: var(--im-color-primary-light-2);
            color: var(--im-color-white);
            min-width: 30px;
            height: 100%;
            min-height: 35px;
            //width: 90%;
            //white-space: pre-wrap;
            //word-break: break-all;

            &:after {
              left: auto;
              right: -10px;
              border-top-color: var(--im-color-primary-light-2);
            }
          }

          .chat-msg-image {
            flex-direction: row-reverse;
          }

          .chat-msg-file {
            flex-direction: row-reverse;
          }

          .chat-action {
            flex-direction: row-reverse;

            .iconfont {
              transform: rotateY(180deg);
            }
          }
        }
      }
    }

  }
}

::v-deep .el-button.el-button--text {
  padding: 0 !important;
}
</style>
